// pages/sign/sign.js
import {request} from '../../request/index.js'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min");
var qqmapsdk;
var util = require('../../utils/jingweiduzhuanhuan')  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    newChkForm:{
      chkType: '',
      dgeId: '',
      chkInfo: '',
      empId: '',
      chkLng: '',
      chkLat: ''
    },
    EndChkForm:{
      chkId: ' ',  // 此次巡视记录的ID
      chkLng: '',
      chkLat: ''
    },
    addressDetail: "信号较弱，难以解析", //详细地址
    address: "",//推荐显示地址
    longitude: "", //经度
    latitude: "" , // 纬度
    CreateTime:'', // 签到时间
    EndTime: '', // 签退时间
    start: '',
    doing: '',
    day: '', // 巡视持续时间/天时分秒
    minutes: '',
    hours: '',
    seconds: '',
    chkLng: '',
    chkLat: '',
    chkId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(wx.getStorageSync('token'))
    // test
    // this.calculationDate('2021-01-29 20:34:21','2021-01-29 20:37:21')
    qqmapsdk = new QQMapWX({
      key: 'TUHBZ-ZPFKU-XQAVA-BC4M4-ER4IZ-BXBLL'
    });
    // this.getJingWeiDu();
    if (options){
      // wx.setStorageSync('checkDgeId', options.dgeId)
      this.setData({
        "newChkForm[0].dgeId": wx.getStorageSync('checkDgeId') ? wx.getStorageSync('checkDgeId') : options.dgeId,
        // start: wx.getStorageSync('checked') ? wx.getStorageSync('checked') : true,
        // doing: wx.getStorageSync('doing') ? wx.getStorageSync('doing') : false
        start: true,
        doing: false
      })
    }
  },

  /**
   * 获取经纬度
   */
  getJingWeiDu(e) {
    var type = e.currentTarget.dataset.type
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        var lat = res.latitude
        var lng = res.longitude
        console.log(lat + "||latitude" );
        console.log(lng + "||longitude");
        // wgs84转百度坐标系(wgs->gcj->baidu)
        // var gcj = util.transformFromWGSToGCJ(lat,lng)
        var baidu = util.transformFromGCJToBaidu(lat,lng)
        console.log('baidu:'+baidu)
        // console.log('gcj:' + gcj);
        that.setData({
          longitude: baidu.longitude,
          latitude: baidu.latitude
        }, () => {
          // that.jingWeiduToDiZhi(res.latitude,res.longitude);
          that.jingWeiduToDiZhi(that.data.latitude,that.data.longitude);
          // if(that.data.start) {
          //   that.getPos()
          // }
          // else {
          //   that.getEndPos()
          // }
          if(type === 'sign') {
            that.getPos()
          }
          else {
            that.getEndPos()
          }
        });
      }
    })
  },
  /**
   * 经纬度转换成地址
   */
  jingWeiduToDiZhi(lat, lng) {
    let that = this;
    // 调用接口
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: lat,
        longitude: lng
      },
      coord_type:3,
      success: function(res){
        console.log(res);
        // let tempData = res.result.address_component;
        that.setData({
          addressDetail: res.result.address?res.result.address: '',
          address: res.result.formatted_addresses.recommend ? res.result.formatted_addresses.recommend : '当前信号较弱，无法解析'
        });
      },
      fail: function(error) {
        console.log("err")
        console.error(error);
      },
      complete: function(res) {
        // console.log(res);
      }
    })
  },
  async getPos(){
      // console.log(this.data.longitude)
      this.setData({
        "newChkForm[0].chkLng": this.data.longitude,
        "newChkForm[0].chkLat": this.data.latitude,
        // "newChkForm[0].chkLng": 121.417382,
        // "newChkForm[0].chkLat": 28.667601,
        "newChkForm[0].chkType": 'general'
      })
    console.log(this.data.newChkForm[0])
    const res = await request({
      url: '/check/create',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      data: this.data.newChkForm[0],
      method: "post",
    })
    console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2500
      })
    }
    else {
      // wx.setStorageSync('checked', false)
      // wx.setStorageSync('doing', true)
      this.setData({
        start: false,
        doing: true,
        createTime: res.data.data.createTime,
        "EndChkForm[0].chkId": res.data.data.chkId
      })
    }
  },
  async getEndPos(){
    this.setData({
      // "EndChkForm[0].chkLat": 28.667601,
      // "EndChkForm[0].chkLng": 121.417382
      "EndChkForm[0].chkLat": this.data.latitude,
      "EndChkForm[0].chkLng": this.data.longitude
    })
    console.log(this.data.EndChkForm[0])
    var that = this
    const res = await request({
      url: '/check/chkEnd',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      data: that.data.EndChkForm[0],
      method: "put",
    })
    console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2500
      })
    }
    else {
      // wx.setStorageSync('checked', true)
      // wx.setStorageSync('doing', false)
      that.setData({
        start: true,
        doing: false
      }, () => {
        that.Check(that.data.EndChkForm[0].chkId)
        console.log(that.data.EndChkForm[0].chkId)
      })
    }
  },
 async Check(id){
   var that = this
    const res = await request({
      url: '/check/findById/'+ id ,
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })// console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }else{
      var list = res.data.data
      console.log(list)
      that.setData({
        chkLng: list.chkLng,
        chkLat: list.chkLat,
        chkId: list.chkId,
        CreateTime: list.createTime
      },() => {
        wx.redirectTo({
          url: '/pages/finish/finish?chkId=' + list.chkId + '&chkLat=' + list.chkLat + '&chkLng=' + list.chkLng + '&chkMin=' + list.chkMin + '&endTime=' + list.endTime
        // that.calculationDate(list.createTime,list.endTime)
      })
    })
    }
  },
  calculationDate(startTime,endTime) {
    startTime = startTime.substring(0,19)
    startTime = startTime.replace(/-/g,'/')
    endTime = endTime.substring(0,19)
    endTime = endTime.replace(/-/g,'/')
    var dateBegin = new Date(startTime)
    var dateEnd = new Date(endTime)
    var dateDiff = dateEnd.getTime() - dateBegin.getTime()
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
    var leave1=dateDiff%(24*3600*1000)
    var hours=Math.floor(leave1/(3600*1000))
    var leave2=leave1%(3600*1000)
    var minutes=Math.floor(leave2/(60*1000))
    var leave3=leave2%(60*1000);
    var seconds=Math.round(leave3/1000)
    this.setData({
      day: dayDiff,
      hours: hours,
      minutes:minutes,
      seconds:seconds
    }, () => {
       wx.redirectTo({
      url: '/pages/finish/finish?chkId=' + this.data.chkId + '&chkLat=' + this.data.chkLat + '&chkLng=' +this.data.chkLng + '&day=' + this.data.day + '&hours=' + this.data.hours + '&minutes='+ this.data.minutes + '&seconds=' + this.data.seconds + '&updateTime=' + endTime
      // test
      // url: '/pages/finish/finish?chkId=' + 10 + '&chkLat=' + 28.371800 + '&chkLng=' +121.385990 + '&day=' + 0 + '&hours=' + 1 + '&minutes='+ 15 + '&seconds=' + 30 + '&updateTime=' + '2021-01-29 20:34:21'
     })
    }
   )
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if ( wx.getStorageSync('token')){
      this.checkToken()
    }
    else {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
    this.setData({
      "newChkForm[0].empId": wx.getStorageSync('empId')
    })
  },
  async checkToken(){
    var token = wx.getStorageSync('token')
    if (token){
      const res = await request({
        url: '/user/verify',
        header:{
          'Authorization':'Bearer '+ token,
        },
        method: "get",
      })
      if (res.data.status !== 200){
         var title = res.data.msg ? res.data.msg :null
        if (title){
        wx.showToast({
          title: title,
          icon: 'none',
          duration: 2000
          })
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    } 
  }
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})